/*******************************************************************************
 * Copyright (c) 2000, 2010 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.karelun.ideaboard.gef.ui.actions;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.action.IAction;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.actions.RetargetAction;
import org.eclipse.ui.part.MultiPageEditorActionBarContributor;

/**
 * Contributes actions to the workbench. !!Warning: This class is subject to
 * change.
 */
public abstract class ActionBarContributor extends MultiPageEditorActionBarContributor {

	private ActionRegistry registry = new ActionRegistry();

	private List<IAction> retargetActions = new ArrayList<IAction>();

	private List<String> globalActionKeys = new ArrayList<String>();

	public void init(IActionBars bars) {
		createActions();
		declareGlobalActionKeys();
		super.init(bars);
	}

	protected abstract void createActions();
	
	protected abstract void declareGlobalActionKeys();
		
	protected IAction getAction(String id) {
		return registry.getAction(id);
	}
	
	protected void addRetargetAction(RetargetAction action) {
		registry.registerAction(action);
		retargetActions.add(action);
		getPage().addPartListener(action);
		addGlobalActionKey(action.getId());
	}
	
	protected void addGlobalActionKey(String key) {
		globalActionKeys.add(key);
	}

	public void setActiveEditor(IEditorPart editor) {
		ActionRegistry registry = (ActionRegistry) editor.getAdapter(ActionRegistry.class);
		IActionBars bars = getActionBars();
		for (int i = 0; i < globalActionKeys.size(); i++) {
			String id = globalActionKeys.get(i);
			IAction actionHandler = registry.getAction(id);
			bars.setGlobalActionHandler(id, actionHandler);
		}
	}
	
	@Override
	public void setActivePage(IEditorPart activeEditor) {
		// Do nothing
	}
	
	public void dispose() {
		for (int i = 0; i < retargetActions.size(); i++) {
			RetargetAction action = (RetargetAction) retargetActions.get(i);
			getPage().removePartListener(action);
			action.dispose();
		}
		registry.dispose();
		retargetActions = null;
		registry = null;
	}
}
